import re
# 补充JWT登陆请求后返回的字段
# 定义补充字段的函数
from django.contrib.auth.backends import ModelBackend

from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """自定义jwt认证成功返回数据"""
    return {
        'token': token,  # 登陆状态token
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    根据账号获取user对象
    :param account: 账号，可以是用户名，也可以是手机号
    :return: User对象 或者 None
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 账号为手机号
            user = User.objects.get(mobile=account)
        else:
            # 账号为用户名
            # django.db.utils.InternalError: (1054, "Unknown column 'tb_users.default_address_id' in 'field list'")
            user = User.objects.get(username=account)
            print(user)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户名或手机号认证"""
    # AttributeError: type object 'User' has no attribute 'DoesNotExit'
    # ERROR basehttp 124 "POST /authorizations/ HTTP/1.1" 500 25262
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user










